<?php
/**
 * Created by PhpStorm.
 * User: xeng
 * Date: 2018/1/20
 * Time: 17:20
 * 数据统计 类
 */
namespace Home\Controller;
use Think\Controller;
class StatsController extends AuthController
{

    protected $con ='DB_CONFIG1';
    public function index()
    {

        $this->display('mail');
    }

    public function getliucun(){
      /*  G('begin');
        // var_dump(cal_days_in_month(CAL_GREGORIAN,5,2018));
        $this->CheckPower('6001');
        $r=$this->actionLog('全部','查询了','留存统计');
        $condi=$_GET;
        $condi=array_merge($condi,$_POST);
        $limit = (int)10;
        $p=$condi['p']?(int)$condi['p']-1:(int)0;
        $skip=$p*$limit;
        $p=$condi['p']?(int)$condi['p']:(int)1;
        $where =' 1=1 ';
        $today=date("Y-m-d",time());
        if($condi['start_time']){
            $where .= ' and time >= "'.$condi['start_time'].' 00:00:00"';

        }
        if($condi['end_time']){
            $where .= ' and time <= "'.$condi['end_time'].' 23:59:59"';
        }else{
            $condi['start_time'] =$today;
            $condi['end_time'] =$today;
        }
        // 1 查询留存数据库  今日数据是否有

        $todayLiuCun=$this->weblog("SELECT id FROM data_liucun WHERE time='$today'");

        if($todayLiuCun){  //今日之前数据已经存入  只需修改七日留存为空的数据
            if($p==1){
                $sevenLiuCun=$this->weblog('SELECT time FROM data_liucun WHERE d6 = \'0%\' ORDER by time ');
                $sevenTime=substr($sevenLiuCun[0]['time'],0,10);
                $ToWhere ='';
                $ToWhere .= ' and (logtime between "'.$sevenTime.' 00:00:00"  and  "'.$today.' 23:59:59") ';
                $Tolist=$this->gamelog("SELECT m.time as timea ,count(m.id) as log_loginout  FROM (SELECT id,SUBSTR(logtime,1,10) as time FROM log_loginout where logtype=0 and serverid=20  $ToWhere GROUP BY SUBSTR(logtime,1,10) , gameid ORDER BY logtime DESC ) m  GROUP BY m.time");

                foreach ($Tolist as $key => $value) {
                    $this->regpoe($value['timea'],$value['log_loginout']);
                }
            }


            ///统计好的数据
            $result=$this->weblog("SELECT *,SUBSTR(time,1,10)  as timea  FROM data_liucun WHERE $where  ORDER by time desc limit $skip,$limit");
            $count=$this->weblog("SELECT id FROM data_liucun where $where");

            $page_show = $this->page_show(count($count),$limit,$p);
            $shows=$page_show;
            $pg=array_pop($shows);
            $this->assign("totalPages",$pg);
            $this->assign("p",$p);
            $this->assign("condi",$condi);
            $this->assign("count",count($count));
            $this->assign('lists',$result);
            G('end');
            echo G('begin','end').'s';
            $this->display();
            die();
        }else{  ///今日不存在  需要填入最后一条数据 到今日的数据
            $OtherDay=$this->weblog("SELECT time FROM data_liucun   ORDER by time DESC ");
            $OtherTime=substr($OtherDay[0]['time'],0,10);
            $YesTeDay= date("Y-m-d",strtotime('+1 days',strtotime(''.$OtherTime.'')));    ////获取最后一个时间的第二天时间
            $ToWhere ='';
            $ToWhere .= '  (logtime between "'.$YesTeDay.' 00:00:00"  and  "'.$today.' 23:59:59") ';
            $Tolist=$this->gamelog("SELECT m.time as timea ,count(m.id) as login_count  FROM (SELECT id,SUBSTR(logtime,1,10) as time FROM log_loginout where  logtype=0 and serverid=20 and $ToWhere  GROUP BY SUBSTR(logtime,1,10), gameid ORDER BY logtime DESC ) m  GROUP BY m.time");

            foreach ($Tolist as $key => $value) {
                $insert=$this->weblog("INSERT INTO data_liucun (time,login_peo) VALUES ('".$value['timea']."',".$value['login_count'].")");
                $this->regpoe($value['timea'],$value['login_count']);
            }

            $result=$this->weblog("SELECT *,SUBSTR(time,1,10)  as timea  FROM data_liucun ORDER by time desc limit $skip,$limit");
            $count=$this->weblog("SELECT id FROM data_liucun");
            $page_show = $this->page_show(count($count),$limit,$p);
            $shows=$page_show;
            $pg=array_pop($shows);
            $p=$condi['p']?(int)$condi['p']:(int)1;
            $this->assign("totalPages",$pg);
            $this->assign("condi",$condi);
            $this->assign("p",$p);
            $this->assign("count",count($count));
            $this->assign('lists',$result);
            G('end');
            echo G('begin','end').'s';
            $this->display();
            die();
        }*/
        $useraccount = M('');
        $url = pageurl(__SELF__);
        $pagesize = empty($url['limit'])?90:$url['limit'];
        $page = empty($url['page'])?1:$url['page'];
        $state = ($page-1)*$pagesize;
        if(!empty($url['starttime']) && !empty($url['endtime'])){
            $where['time'] = array('between',array($url['starttime'],$url['endtime']));
        }
        $list = $useraccount->table('data_liucun')->where($where)->order('time desc')->limit($state,$pagesize)->select();
        $count=count($list);
        $data['code'] = 0;
        $data['message'] = '';
        $data['count'] = $count;
        $data['data'] = $list;
        $this->ajaxReturn($data,'json');
    }

    public function updatekeep(){
        $today=date("Y-m-d",time());
        $useraccount = M('');
        $gamelog = M('','','DB_CONFIG2');
        $where['time'] = array('eq',$today);
        $list = $useraccount->table('data_liucun')->field('time')->where($where)->order('time DESC')->select();
        if(!empty($list)){

            $sevenLiuCun=$this->weblog('SELECT time FROM data_liucun WHERE d6 = \'0%\' ORDER by time desc LIMIT 7');
            $sevenTime=$sevenLiuCun[count($sevenLiuCun)-1]['time'];
            $ToWhere ='';
            $ToWhere .= ' and (logtime between "'.$sevenTime.' 00:00:00"  and  "'.$today.' 23:59:59") ';
            $Tolist=$this->gamelog("SELECT m.time as timea ,count(m.id) as log_loginout  FROM (SELECT id,SUBSTR(logtime,1,10) as time FROM log_loginout where logtype=0 and serverid=20  $ToWhere GROUP BY SUBSTR(logtime,1,10) , gameid ORDER BY logtime DESC ) m  GROUP BY m.time");

            foreach ($Tolist as $key => $value) {
                $this->regpoe($value['timea'],$value['log_loginout']);
            }
        }else{
            $list = $useraccount->table('data_liucun')->field('time')->order('time DESC')->select();
            if(empty($list)){
               $log = $gamelog->table("log_loginout")->field('DATE_FORMAT(logtime,\'%Y-%m-%d\') as logtime ')->order('logtime')->find();
                $YesTeDay =  $log['logtime'];

            }else{
                $OtherTime= $list[0]['time'];
                $YesTeDay= date("Y-m-d",strtotime('+1 days',strtotime(''.$OtherTime.'')));
            }

            $ToWhere ='';
            $ToWhere .= ' (logtime between "'.$YesTeDay.' 00:00:00"  and  "'.$YesTeDay.' 23:59:59") ';

            $Tolist= $gamelog->table("(SELECT id,SUBSTR(logtime,1,10) as time FROM log_loginout where  logtype=0 and serverid=20 and $ToWhere  GROUP BY SUBSTR(logtime,1,10), gameid ORDER BY logtime DESC ) m ")->field('m.time as timea ,count(m.id) as login_count')->group('m.time')->select();
            if(!empty($Tolist)){
                foreach ($Tolist as $key => $value) {
                    $insert=$this->weblog("INSERT INTO data_liucun (time,login_peo) VALUES ('".$value['timea']."',".$value['login_count'].")");
                    $this->regpoe($value['timea'],$value['login_count']);
                }
            }else{
                $insert=$this->weblog("INSERT INTO data_liucun (time,login_peo) VALUES ('".$YesTeDay."',0)");
            }

        }

        $data['code'] = 0;
        $data['msg'] = $Tolist;
        $data['data'] = $list;
        $this->ajaxReturn($data);
    }


    /*
     * 留存统计
     */
    public function keep(){
        $this->display('liucun');
    }

    //查询注册 统计
    public  function regpoe($time,$login_count){
        // $time=$_GET['atime'];
        $where ='1=1';
        if($time){
            $where = '  (logtime between "'.$time.' 00:00:00"  and  "'.$time.' 23:59:59") ';
        }
        $listsm=$this->gamelog("SELECT  count(m.id) as reg_count  FROM (SELECT id,SUBSTR(logtime,1,10) as time FROM log_loginout WHERE logtype = 4 and serverid=20 and  $where GROUP BY SUBSTR(logtime,1,10), gameid ) m  GROUP BY m.time");
        $timeas=$time;
        $reg_count=$listsm[0]['reg_count']?$listsm[0]['reg_count']:0;
        $result=$this->GetKeepHistory($time,$listsm[0]['reg_count']);
        $rows=$this->weblog('UPDATE data_liucun set login_peo='.$login_count.',reg_count='.$reg_count.',d1="'.$result['d1'].'",d2="'.$result['d2'].'",d3="'.$result['d3'].'",d4="'.$result['d4'].'",d5="'.$result['d5'].'",d6="'.$result['d6'].'" WHERE time="'.$timeas.'"');
    }


    function GetKeepHistory($day,$reg_count){
        $time[] = Date("Y-m-d H:i:s", strtotime($day));        //今天   
        $time[] = Date("Y-m-d",strtotime($day)+(1*24*60*60) ); //  次日 留存
        $time[] = Date("Y-m-d",strtotime($day)+(2*24*60*60) ); //  3日留存
        $time[] = Date("Y-m-d",strtotime($day)+(3*24*60*60) ); // 第4天     
        $time[] = Date("Y-m-d",strtotime($day)+(4*24*60*60) ); // 第5天     
        $time[] = Date("Y-m-d",strtotime($day)+(5*24*60*60) ); // 第6天    
        $time[] = Date("Y-m-d",strtotime($day)+(6*24*60*60) ); // 第7天     
        //查询当天注册的用户  
        $user_sets=[];
        $onusers=$this->gamelog("SELECT  gameid from log_loginout  WHERE SUBSTR(logtime,1,10) ='".$day."'  and  logtype = 4 GROUP BY gameid");
        $_onusers=[];
        foreach ($onusers as  $value) {
            $_onusers[]=$value['gameid'];
        }

        $user_sets[]=$_onusers;
        //查询各个留存时间   登陆的用户
        for($i=1;$i<count($time);$i++){
            $users =  $this->gamelog("SELECT  gameid from log_loginout  WHERE SUBSTR(logtime,1,10) ='".$time[$i]."'  and serverid=20 and  logtype = 0  GROUP BY gameid");
            $_users=[];
            foreach ($users as  $value) {
                $_users[]=$value['gameid'];
            }
            $set1=$_users;   ///登陆
            $set2=$user_sets[0];   /// 注册
            $set=array_intersect($set1,$set2);
            $successRate = floor(((int)count($set)/(int)$reg_count)*10000)/10000*100;
            $results = $successRate.'%';
            $result['d'.$i]= $results;
        }
        return $result;
    }

    /*
    * 游戏   统计
    */
    public function brnn(){
        $this->CheckPower('5001');
        $this->assign('selects', $this->selects());
        $this->assign('time', date('Y-m-d'));
        $this->display('game_brnn');
    }

    public function getbrnn(){
        S(array('type'=>'file','prefix'=>'stats','expire'=>60*60*24));
        $useraccount = M('','',"DB_CONFIG2");
        $url = pageurl(__SELF__);
        $pagesize = empty($url['limit'])?90:$url['limit'];
        $page = empty($url['page'])?1:$url['page'];
        $state = ($page-1)*$pagesize;
        $where2['logtype'] = array('eq','0');
        $where2['serverid'] = array(array('neq',0),array('neq',20),'and');
        if(!empty($url['time']) && !empty($url['end_time'])){
            $where['time'] = array('between',array($url['time'],$url['end_time']));
            $time=$url['time'];
        }else{
            $time = date('Y-m-d');
            $where['time'] = array('eq',$time);
        }
        if(!empty($url['status']) && $url['status'] != "-1"){
            $where['serverid'] = array('in',$this->getserverid($url['status']));
        }

        if($time == date('Y-m-d')){
            $list = $useraccount->table('view_statistics')->where($where)->limit($state,$pagesize)->select();
            $count=count($list);
            foreach ($list as $key => $value) {
                $list[$key]["ServerName"] =$this->getServerName($value['serverid']);
            }
        }else{
            $list = S('game_record_stats'.$page.$pagesize.$url['time']);
            $count = S('game_record_stats_count'.$url['time']);
            if(empty($list) || $count < 1){
                $list = $useraccount->table('view_statistics')->where($where)->limit($state,$pagesize)->order('time')->select();
                $count=count($list);
                if(!empty($list)){
                    foreach ($list as $key => $value) {
                        $list[$key]["ServerName"] =$this->getServerName($value['serverid']);
                    }
                  S('game_record_stats'.$page.$pagesize.$url['time'],$list);
                  S('game_record_stats_count'.$url['gameid'],$count);
                }
            }
        }



        $data['code'] = 0;
        $data['message'] = '';
        $data['count'] = $count;
        $data['data'] = $list;
        $this->ajaxReturn($data,'json');
    }


    public function updatebrnn(){

    }


    public function update_game(){
        $useraccount = M('','',"DB_CONFIG2");
        $beginy = date('Y-m-d',strtotime('-1 day'));
        $where['time']= array('eq',$beginy);
        $s = $useraccount->table('game_players')->where($where)->count();
        if($s <1){

            $wheres['time'] = array('between',array($beginy.' 00:00:00',$beginy.' 23:59:59'));
            $where2['logtime'] = array('between',array($beginy.' 00:00:00',$beginy.' 23:59:59'));

            $list = $useraccount->table('game_player')->field("COUNT(DISTINCT gameid) count,COUNT(serverid) scount,DATE_FORMAT(time,'%Y-%m-%d') time, CONVERT(SUM(tax)/1000,DECIMAL(12,2)) tax,CONVERT(SUM(betscore)/1000,DECIMAL(12,2)) betscore,CONVERT(SUM(caculscore)/1000,DECIMAL(12,2)) caculscore ,serverid ,CONVERT(SUM(rewardscore)/1000,DECIMAL(12,2)) rewardscore")->where($wheres)->group("serverid,DATE_FORMAT(time,'%Y-%m-%d')")->select();
            $list2 = $useraccount->table('log_loginout')->field("COUNT(DISTINCT gameid) count,COUNT(serverid) scount,DATE_FORMAT(logtime,'%Y-%m-%d') AS time,serverid")->where($where2)->group("serverid,DATE_FORMAT(logtime,'%Y-%m-%d')")->select();
            $count=count($list);
            $count2=count($list2);
            if($count >= $count2){
                foreach ($list as $key => $value) {
                    foreach ($list2 as $v){
                        if($value['serverid'] == $v['serverid'] && $value['time'] == $v['time']){
                            $list[$key]["count"] =$v['count'];
                            $list[$key]["scount"] =$v['scount'];
                        }
                    }
                    $list[$key]["ServerName"] =$this->getServerName($value['serverid']);   //游戏房间名称
                }
            }else{
                foreach ($list2 as $v){
                    foreach ($list as $key => $value) {
                        if ($value['serverid'] == $v['serverid'] && $value['time'] == $v['time']) {
                            $list[$key]["count"] = $v['count'];
                            $list[$key]["scount"] = $v['scount'];
                        }
                        $list[$key]["ServerName"] =$this->getServerName($value['serverid']);
                    }

                    $a=array_search($v['serverid'],array_column($list,'serverid'));
                    if($a === false){
                        $d['time']=$v['time'];
                        $d['serverid']=$v['serverid'];
                        $d['ServerName']= $this->getServerName($v['serverid']);
                        $d['count']=$v['count'];
                        $d['scount']=$v['scount'];
                        $d['betscore']=0;
                        $d['rewardscore']=0;
                        $d['tax']=0;
                        $d['caculscore']=0;
                        array_push($list,$d);
                    }
                }

            }
        }
    }



    function runtime($mode = 0){
        static $t;
        if(!$mode){
            $t = microtime();
            return;
        }
        $t1 = microtime();
        list($m0,$s0) = split("  ",$t);
        list($m1,$s1) = split("  ",$t1);

        return sprintf("%.3f ms",($s1+$m1-$s0-$m0)*1000);
    }

    //ajax分条查询
    public function get_one_info(){
        $seid= $_GET['severid'];
        $time= $_GET['time'];

        if($time){
            // $t1=$time.' 00:00:00"';
            // $t2=$time.' 23:59:59"';
            // $where .= ' time_virtual>= "'.$t1;
            // $where .= ' and time_virtual<= "'.$t2;
            $where .= '  (time_virtual between "'.$time.' 00:00:00"  and  "'.$time.' 23:59:59") ';
        }
        $res=$this->gamelog("SELECT serverid_virtual,time_virtual,SUM(JSON_EXTRACT(log, '$.caculScore')) as amount,
                            SUM(JSON_EXTRACT(log, '$.betScore')) as bet,
                            SUM(JSON_EXTRACT(log, '$.tax')) as tax  FROM game_player  
                            where $where AND serverid_virtual=".(int)$seid."  GROUP BY serverid_virtual");
        $result['amount']=0;
        $result['tax']=0;
        $result['servid'] = $_GET['severid'];
        $result['kj']=0;
        $result['bet']=0;
        if($res){
            foreach ($res as $key => $value) {
                $result['amount']+=(-$value['amount']);   ////盈亏
                $result['tax']+=$value['tax'];     //税收
                // if(is_object($value['bet'])){
                //      $b=get_object_vars($value['bet'])['value'] ;
                //      $result['bet']=$b;    //总下注金额
                // }else{
                $result['bet']+=$value['bet'];    //总下注金额
                // }
                $result['kj']+=($value['bet']+$value['amount']);  ///开奖
                $result['tax']+=$value['tax'];  //税
            }
        }
        $bet=$result['bet'];
        $tax=$result['tax'];
        $amount=$result['amount'];
        $mysql=$this->weblog("UPDATE game_statistics set bet=$bet,tax=$tax,amount=$amount,status=1 WHERE severID=$seid and time='$time'");
        $this->ajaxReturn($result);
    }

    //游戏服务器
    public function selects(){
        $str[] = ['kindid'=>2,'name'=>'抢庄牛牛'];
        $str[] = ['kindid'=>3,'name'=>'通比牛牛'];
        $str[] = ['kindid'=>5,'name'=>'百人牛牛'];
        $str[] = ['kindid'=>10,'name'=>'通比炸金花'];
        $str[] = ['kindid'=>20,'name'=>'百人炸金花'];
        $str[] = ['kindid'=>30,'name'=>'炸金花'];
        $str[] = ['kindid'=>50,'name'=>'幸运水果机'];
        $str[] = ['kindid'=>60,'name'=>'百家乐'];
        $str[] = ['kindid'=>61,'name'=>'龙虎斗'];
        $str[] = ['kindid'=>62,'name'=>'红黑大战'];
        $str[] = ['kindid'=>65,'name'=>'21点'];
        $str[] = ['kindid'=>80,'name'=>'财神来了'];
        $str[] = ['kindid'=>81,'name'=>'水浒传'];
        return $str;
    }

}